package sz.szsmk.citizencard.ui.adapter;

import android.content.Context;
import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.PagerAdapter;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.model.network.bean.response.CardInfo;
import sz.szsmk.citizencard.model.network.bean.response.QueryUserCardResponse;
import sz.szsmk.citizencard.ui.activity.RoutineCardDetailActivity;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.JumpUtils;
import sz.szsmk.citizencard.util.StringUtils;
import sz.szsmk.citizencard.widget.BlurringView;

public class CardAdapter extends PagerAdapter {

    private ArrayList<ArrayList<QueryUserCardResponse.DataBean>> mendList;

    private Context mContext;

    private TextView homeCardName;
    private TextView homeCardBalance;
    private TextView homeCardId;
    private TextView cardSize;
    private LinearLayout homeBind;
    private ArrayList<CardInfo> cardInfoList;
    private RecyclerView cardViewRv;
    private ArrayList<String> openList;
    private CheckBox eyrCheck;
    private BlurringView blurItemCard;
    private TextView card_view_user;

    private View homeBg;

    private PagerOnItemClickListener pagerClickListener;
    private PagerOnCardNickNameClickListener pagerOnCardNickNameClickListener;

    private List<View> viewList;

    private boolean needCardUserName = false;

    private int currentPosition = 0;//默认选择第一个页面
//    private String string;

    public CardAdapter(Context mContext, ArrayList<ArrayList<QueryUserCardResponse.DataBean>> mendList, View homeBg, boolean needCardUserName) {
        this.mContext = mContext;
        this.mendList = mendList;
        this.homeBg = homeBg;
        this.needCardUserName = needCardUserName;
        viewList = new ArrayList<>();
    }

    public void setCurrentPosition(int position) {
        this.currentPosition = position;
    }

    /**
     * 设置卡片点击事件
     *
     * @param pagerClickListener
     */
    public void setPagerClickListener(PagerOnItemClickListener pagerClickListener) {
        this.pagerClickListener = pagerClickListener;
    }

    /**
     * 设置卡
     *
     * @param pagerOnCardNickNameClickListener
     */
    public void setPagerOnCardNickNameClickListener(PagerOnCardNickNameClickListener pagerOnCardNickNameClickListener) {
        this.pagerOnCardNickNameClickListener = pagerOnCardNickNameClickListener;
    }

    /**
     * 更新视图
     *
     * @param position
     */
    public void invalidateBlurView(int position) {
        if (viewList == null) {
            return;
        }

    }

    @Override
    public int getCount() {
        return null == mendList ? 0 : mendList.size();
    }


    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public synchronized Object instantiateItem(ViewGroup container, final int position) {
        View view;
        if (viewList.size() == position) {
            view = LayoutInflater.from(mContext).inflate(R.layout.card_item_view, null, false);
            viewList.add(view);
        } else {
            view = viewList.get(position);
        }
        view.setTag(position);
//            PubUtils.popTipOrWarn(mContext,position+"");
        eyrCheck = (CheckBox) view.findViewById(R.id.card_view_eye);

        ArrayList<QueryUserCardResponse.DataBean> been = (ArrayList<QueryUserCardResponse.DataBean>) mendList.get(position);
        cardInfoList = new ArrayList<>();

        openList = new ArrayList<>();
        for (int i = 0; i < been.size(); i++) {
            String stateName = been.get(i).getStateName();
            if (stateName != null) {
                if (stateName.equals("已开通")) {
                    //获取已开通的功能卡名称
                    String funcName = been.get(i).getFuncName();
                    openList.add(funcName);
                }
            }
        }

        if (been != null) {
            for (int i = 0; i < been.size(); i++) {
                QueryUserCardResponse.DataBean dataBean = been.get(i);
                String json = new Gson().toJson(dataBean);
                CardInfo info = new Gson().fromJson(json, CardInfo.class);
                cardInfoList.add(info);
            }

            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (pagerClickListener != null) {
                        pagerClickListener.onItemClick(position, view);
                    }
                }
            });

            homeCardName = (TextView) view.findViewById(R.id.home_card_name);
            homeCardBalance = (TextView) view.findViewById(R.id.home_card_balance);
            homeCardId = (TextView) view.findViewById(R.id.home_card_id);
            cardSize = (TextView) view.findViewById(R.id.home_card_size);
            card_view_user = (TextView) view.findViewById(R.id.card_view_user);


            if (mendList != null) {
                cardSize.setText("已绑定" + mendList.size() + "张");
            }

            cardViewRv = (RecyclerView) view.findViewById(R.id.card_view_rv);
            LinearLayoutManager manager = new LinearLayoutManager(mContext);
            manager.setOrientation(LinearLayoutManager.HORIZONTAL);
            cardViewRv.setLayoutManager(manager);
            CardViewFunAdapter funAdapter = new CardViewFunAdapter(DaggerApplication.getIns(), openList);
            cardViewRv.setAdapter(funAdapter);

            homeBind = (LinearLayout) view.findViewById(R.id.home_bind);
            //从市民卡绑卡进入 加号隐藏
            if (Constant.isBind) {
                homeBind.setVisibility(View.VISIBLE);
            } else {
                homeBind.setVisibility(View.GONE);
            }
            homeBind.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Bundle bundle = new Bundle();
                    bundle.putString("key", "home");
                    JumpUtils.jumptoNatvie(mContext, "addnewcard", 0, bundle);
                }
            });
            ArrayList<QueryUserCardResponse.DataBean> dataBeen = mendList.get(position);
            final QueryUserCardResponse.DataBean dataBean = dataBeen.get(0);
            String cardNo = dataBean.getBindCardNo();
            String hideMidStr2 = StringUtils.getHideMidStr2(cardNo);

            StringBuilder str = new StringBuilder(cardNo.replace(" ", ""));

            int i = str.length() / 4;
            int j = str.length() % 4;

            for (int x = (j == 0 ? i - 1 : i); x > 0; x--) {
                str = str.insert(x * 4, " ");
            }

            homeCardId.setText(str);
            if (dataBean != null) {
                double balance = (double) dataBean.getCardTotalBalance();
                double mBalance = balance / 100;
                String balancestr = doubleToString(mBalance);
                homeCardBalance.setTextSize(30);
                homeCardBalance.setText(eyrCheck.isChecked() ? "* * * * * *" : balancestr);
            }


            homeCardName.setText(dataBean.getCardTypeName());
            if (dataBean.getCustName() == null || dataBean.getCustName().equals("")) {
                card_view_user.setText(dataBean.getCardNickName());
            } else {
                card_view_user.setText(getUserInfo(dataBean));
            }
            //首页隐藏 详情展示
//            card_view_user.setVisibility(needCardUserName ? View.VISIBLE : View.GONE);

            if (mContext instanceof RoutineCardDetailActivity) {
                card_view_user.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (pagerOnCardNickNameClickListener != null) {
                            pagerOnCardNickNameClickListener.onCardNickNameClick(position, dataBean);
                        }
                    }
                });
            }

            eyrCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    double balance = (double) dataBean.getCardTotalBalance();
                    double mBalances = balance / 100;
                    String balancestr = doubleToString(mBalances);
                    if (balancestr.equals("")) {
                        ((TextView) viewList.get(position).findViewById(R.id.home_card_balance))
                                .setText(isChecked ? "* * * * * *" : balancestr);
                    } else {
                        TextView mBalance = (TextView) viewList.get(position).findViewById(R.id.home_card_balance);

                        if (isChecked) {
                            mBalance.setTextSize(35);
                            mBalance.setMaxLines(2);
                        } else {
                            mBalance.setTextSize(15);
                            mBalance.setMaxLines(2);
                        }
                        mBalance.setText(isChecked ? "* * * * * *" : balancestr);
                    }
                }
            });

            blurItemCard.setBlurredView(homeBg);
            blurItemCard.invalidateData();
            container.addView(view);
        }


        return view;
    }


    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView(viewList.get(position));
    }

    public static String doubleToString(double num) {
        //使用0.00不足位补0，#.##仅保留有效位
        return new DecimalFormat("0.00").format(num);
    }

    public interface PagerOnItemClickListener {
        void onItemClick(int position, View view);
    }

    public interface PagerOnCardNickNameClickListener {
        void onCardNickNameClick(int position, QueryUserCardResponse.DataBean dataBean);
    }

    public void refreshClickCardView(int position, QueryUserCardResponse.DataBean dataBean) {
        mendList.get(position).get(0).setCardNickName(dataBean.getCardNickName());
        Log.d("TAG", "修改后的昵称--> " + dataBean.getCardNickName());
        notifyDataSetChanged();
    }

    private String getUserInfo(QueryUserCardResponse.DataBean dataBean) {
        StringBuilder userInfoStringBuilder = new StringBuilder();
        userInfoStringBuilder.append(dataBean.getCardNickName());
        if (dataBean.getCustName() != null || dataBean.getCustName().equals("")) {
            userInfoStringBuilder.append(" (");
            userInfoStringBuilder.append("持卡人 ");
            userInfoStringBuilder.append(dataBean.getCustName());
            userInfoStringBuilder.append(")");
        }
        return userInfoStringBuilder.toString();
    }


}
